package com.iasku.iaskueleclass_phone.activity;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.iasku.constant.Constant;
import com.iasku.constant.IntentConfig;
import com.iasku.entity.IaskuQuestion;
import com.iasku.entity.UserErrorBook;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.iaskueleclass_phone.Status;
import com.iasku.manager.DataManager;
import com.iasku.manager.IDataManager;
import com.iasku.util.BaseUtil;
import com.iasku.util.IaskuUtil;

/***
 * 错题本题目展示
 */
public class ErrorBookQuestionActivity extends BaseActivity {
    private TextView mQuesInfoTv;
    private WebView mQuesWv;
    private RadioGroup mRadioGroup;
    private RadioButton mTrueBtn, mFalseBtn;
    private LinearLayout mQueChooseLayout;
    private ImageView mPrevBtn, mNextBtn;
    private int mQuestionIndex;
    private IaskuQuestion mIQuestion;
    private CheckBox[] mChoice;
    private LinearLayout mAnswerBtn, mSubmitBtn;
    private boolean choicechange = false;
    private ArrayList<UserErrorBook> mErrorBooks;
    private UserErrorBook mEbook;
    private ImageView mCheckIv;

    private static final int TASK_GET_USERANSWER = 1;
    private static final int TASK_GET_QUESTIONTYPEBYID = 2;
    private static final int TASK_SUBMIT_ERRORANSWER = 3;
    private static final int TASK_START_SYSTEMRECOMMAND = 4;
    
    private int screenWidth;

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        mQuesWv = (WebView) findViewById(R.id.wv_work_question);
        mQuesWv.getSettings().setJavaScriptEnabled(true);
        mQuesWv.getSettings().setSupportZoom(true);
        mQuesWv.getSettings().setBuiltInZoomControls(true);
        mQuesWv.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                // TODO Auto-generated method stub
                super.onPageFinished(view, url);
                mProgressDialog.dismiss();
                mQuesWv.setVisibility(View.VISIBLE);
                setButtonStatus();
            }

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    private void setupView() {
        mQuesInfoTv = (TextView) findViewById(R.id.tv_work_question_info);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_work_question);
        mQueChooseLayout = (LinearLayout) findViewById(R.id.layout_choose);
        mPrevBtn = (ImageView) findViewById(R.id.previous_question_iv);
        mNextBtn = (ImageView) findViewById(R.id.next_question_iv);
        mTrueBtn = (RadioButton) findViewById(R.id.rb_work_question_right);
        mFalseBtn = (RadioButton) findViewById(R.id.rb_work_question_wrong);
        mAnswerBtn = (LinearLayout) findViewById(R.id.btn_work_question_answer);
        mSubmitBtn = (LinearLayout) findViewById(R.id.btn_work_question_submit);
        mCheckIv = (ImageView) findViewById(R.id.iv_work_question_check);
    }

    private void initView() {
        mQuestionIndex = getIntent().getIntExtra(IntentConfig.ERROR_BOOK_POSITION, 0);
        mErrorBooks = getIntent().getParcelableArrayListExtra(IntentConfig.ERROR_BOOK_LIST);
        mEbook = mErrorBooks.get(mQuestionIndex);
        initTitleBar(mEbook.getSubjectname() + " " + mEbook.getQuestionTypeName());
        setupView();
        initWebView();
        addLister();
        mPrevBtn.setVisibility(View.GONE);
        mNextBtn.setVisibility(View.GONE);
        startTask(TASK_GET_USERANSWER);
    }

    private void addLister() {
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                case R.id.rb_work_question_right:
                    choicechange = true;
                    mIQuestion.setUseranswer("T");
                    break;
                case R.id.rb_work_question_wrong:
                    choicechange = true;
                    mIQuestion.setUseranswer("F");
                    break;
                default:
                    choicechange = false;
                    break;
                }
            }
        });

        MyOnClickListener mListener = new MyOnClickListener();
        mPrevBtn.setOnClickListener(mListener);
        mNextBtn.setOnClickListener(mListener);
        mSubmitBtn.setOnClickListener(mListener);
        mAnswerBtn.setOnClickListener(mListener);
    }

    @Override
    protected void onCreate(Bundle saveInstance) {
        // TODO Auto-generated method stub
        super.onCreate(saveInstance);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;
        setContentView(R.layout.errorbook_question_layout);
        initTitleBar();
        initView();
    }

    private class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.previous_question_iv:
                previous();
                break;
            case R.id.next_question_iv:
                next();
                break;
            case R.id.btn_work_question_answer:// 解答
                answer();
                break;
            case R.id.btn_work_question_submit:// 提交
                submit();
                break;
            }
        }
    }

    private void previous() {
        mQuestionIndex--;
        mEbook = mErrorBooks.get(mQuestionIndex);
        getUserAnswer();
    }

    private void getUserAnswer() {
        mBarCenterTitleTv.setText(mEbook.getSubjectname() + " " + mEbook.getQuestionTypeName());
        startTask(TASK_GET_USERANSWER);
    }

    private void next() {
        mQuestionIndex++;
        mEbook = mErrorBooks.get(mQuestionIndex);
        getUserAnswer();
    }

    private void answer() {
        int submitTimes = mIQuestion.getSubmitTimes();
        String attach = mIQuestion.getAttachStr();
        if(submitTimes >= Constant.ERROR_TIMES){
            if(attach == null || "".equals(attach) || "null".equals(attach)){
                BaseUtil.showText(this, "此题没有解答");
                return;
            }
            Intent intent = new Intent();
            intent.setClass(this,ErrorBookQuestionCorrectedAnswerActivity.class);
            intent.putExtra(IntentConfig.ANSWER_ATTACH, attach);
            startActivity(intent);
        }else{
            if(attach == null || "".equals(attach) || "null".equals(attach)){
                openDoing();    // 开始订正-未解答
            }else{
                openSubmit(attach);   // 开始订正-已解答
            }
        }
    }
    
    private void openSubmit(String attach) { 
        Intent intent = new Intent();
        intent.setClass(this,ErrorBookQuestionSubmitAnswerActivity.class);
        intent.putExtra(IntentConfig.ANSWER_ATTACH, attach);
        intent.putExtra(IntentConfig.EXAMID, mEbook.getExamid());
        intent.putExtra(IntentConfig.IQUESTION_INFO,mIQuestion);
        intent.putExtra(IntentConfig.SUBJECT_ID, IaskuUtil.getSubjectId(this, mEbook.getSubjectname()));
        startActivity(intent);
    }

    private void openDoing(){
        mQuesWv.setDrawingCacheEnabled(true);
        mQuesWv.buildDrawingCache();
        Bitmap bmp1 = Bitmap.createBitmap(mQuesWv.getDrawingCache(), 0, 0, screenWidth, mQuesWv.getHeight());
        mQuesWv.destroyDrawingCache();
        if (Constant.questionbt == null)
            Constant.questionbt = Bitmap.createBitmap(screenWidth,  mQuesWv.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas cv = new Canvas(Constant.questionbt);
        cv.drawColor(Color.WHITE);
        Paint p = new Paint();
        p.setColor(Color.WHITE);
        p.setStyle(Paint.Style.STROKE);
        p.setStrokeWidth(1);
        p.setAntiAlias(true);

        cv.drawBitmap(bmp1, 0, 0, p);
        cv.save(Canvas.ALL_SAVE_FLAG);
        bmp1.recycle();
        Intent intent = new Intent();
        intent.setClass(this, ErrorBookQuestionDoingAnswerActivity.class);
        intent.putExtra(IntentConfig.EXAMID, mEbook.getExamid());
        intent.putExtra(IntentConfig.IQUESTION_INFO,mIQuestion);
        intent.putExtra(IntentConfig.SUBJECT_ID, IaskuUtil.getSubjectId(this, mEbook.getSubjectname()));
        startActivity(intent);
    }

    private void submit() {
        int submitTimes = mIQuestion.getSubmitTimes();
        if (submitTimes >= Constant.ERROR_TIMES) {
            BaseUtil.showText(this, "此题已订正，请勿重复订正");
            return;
        }
        if (mIQuestion.getChoicenum() > 0) {
            String myanswer = "";
            for (int i = 0; i < mIQuestion.getChoicenum(); i++) {
                if (mChoice[i].isChecked())
                    myanswer += String.valueOf((char) (65 + i));
            }
            mIQuestion.setUseranswer(myanswer);
        }
        if (choicechange) {
            mIQuestion.setSubmitTimes(submitTimes + 1);
            startTask(TASK_SUBMIT_ERRORANSWER);
        }
    }

    private void setViewValue() {
        choicechange = false;
        setChoiceValue();
        loadUrl();
    }

    private void loadUrl() {
        String loadUrl = Constant.SERVERURL + Constant.WEB_LOAD + mIQuestion.getQuestionno();
        if (mIQuestion.getSubmitTimes() >= Constant.ERROR_TIMES) {
            loadUrl += Constant.QUESTION_STATUS_1;
        } else {
            loadUrl += Constant.QUESTION_STATUS_0;
        }
        mQuesWv.loadUrl(loadUrl);
    }

    private void checkedImg() {
        mQueChooseLayout.addView(mCheckIv);
        mCheckIv.setVisibility(View.VISIBLE);
        String newscore = mIQuestion.getNewscore();
        String getscore = mIQuestion.getUserscore();
        String maxscore = mIQuestion.getQuestion_score();
        if ("".equals(newscore) || "null".equals(newscore)) {
            getscore = mIQuestion.getUserscore();
        } else {
            getscore = mIQuestion.getNewscore();
        }

        if ("0".equals(getscore.trim())) {
            mCheckIv.setImageResource(R.drawable.wrong);
        } else if (getscore.equals(maxscore)) {
            mCheckIv.setImageResource(R.drawable.right);
        } else {
            mCheckIv.setImageResource(R.drawable.wrong);
        }
    }

    private void checkScore() {
        String newscore = mIQuestion.getNewscore();
        String getscore = mIQuestion.getUserscore();
        if ("".equals(newscore) || "null".equals(newscore)) {
            getscore = mIQuestion.getUserscore();
        } else {
            getscore = mIQuestion.getNewscore();
        }
        String maxscore = mIQuestion.getQuestion_score();
        mQuesInfoTv.setText("总共" + mErrorBooks.size() + "题 当前第" + (mQuestionIndex + 1) + "题 本题" + mEbook.getMaxScore()
                + "分  得" + getscore + "分");
        if ("0".equals(getscore.trim())) {
            mQuesInfoTv.setTextColor(Color.RED);
        } else if (getscore.equals(maxscore)) {
            mQuesInfoTv.setTextColor(Color.GREEN);
        } else {
            mQuesInfoTv.setTextColor(getResources().getColor(R.color.work_titleinfo_color));
        }
    }

    private String getAnswer() {
        String answer = mIQuestion.getUseranswer();
        String newanswer = mIQuestion.getNewanswer();
        if ("".equals(newanswer) || "null".equals(newanswer)) {
            answer = mIQuestion.getUseranswer();
        } else {
            answer = mIQuestion.getNewanswer();
        }
        return answer;
    }

    private void setChoiceValue() {
        final int choiceno = mIQuestion.getChoicenum();
        checkScore();
        if (choiceno == 0) {
            if (mIQuestion.getQuestion_type_id() == Constant.TYPE_XUANZ) {
                mQueChooseLayout.removeAllViews();
                if (!"0".equals(mIQuestion.getAnswerid())) {
                    if (getAnswer().startsWith("T"))
                        mTrueBtn.setChecked(true);
                    else if (getAnswer().startsWith("F")) {
                        mFalseBtn.setChecked(true);
                    } else {
                        mTrueBtn.setChecked(false);
                        mFalseBtn.setChecked(false);
                    }
                } else {
                    mTrueBtn.setChecked(false);
                    mFalseBtn.setChecked(false);
                }
                if (mIQuestion.getSubmitTimes() >= Constant.ERROR_TIMES) {
                    mRadioGroup.setEnabled(false);
                } else {
                    mRadioGroup.setEnabled(true);
                }
                mQueChooseLayout.addView(mRadioGroup);
                mQueChooseLayout.setVisibility(View.VISIBLE);
                checkedImg();
                mAnswerBtn.setVisibility(View.GONE);
                mSubmitBtn.setVisibility(View.VISIBLE);
            } else {
                mSubmitBtn.setVisibility(View.GONE);
                mQueChooseLayout.setVisibility(View.GONE);
                mAnswerBtn.setVisibility(View.VISIBLE);
            }
        } else {
            mQueChooseLayout.removeAllViews();
            mChoice = new CheckBox[choiceno];
            for (int i = 0; i < choiceno; i++) {
                mChoice[i] = new CheckBox(this);
                mChoice[i].setText("" + (char) (65 + i));
                mChoice[i].setTextColor(getResources().getColor(R.color.modify_text_left));
                mChoice[i].setButtonDrawable(R.drawable.checkbox_uncheck);
                mChoice[i].setId(1000 + i);
                LinearLayout.LayoutParams lout = new LinearLayout.LayoutParams(screenWidth / 6, LayoutParams.WRAP_CONTENT);
                lout.leftMargin = 20;
                lout.gravity = Gravity.CENTER_VERTICAL;
                mChoice[i].setLayoutParams(lout);
                mChoice[i].setGravity(Gravity.CENTER_VERTICAL);
                mChoice[i].setChecked(false);
                if (mIQuestion.getSubmitTimes() >= Constant.ERROR_TIMES) {
                    mChoice[i].setEnabled(false);
                } else {
                    mChoice[i].setEnabled(true);
                }
                mChoice[i].setOnCheckedChangeListener(new OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        for (int i = 0; i < choiceno; i++) {
                            if (buttonView.getId() == 1000 + i) {
                                if (isChecked) {
                                    choicechange = true;
                                    buttonView.setButtonDrawable(R.drawable.checkbox_checked);
                                } else {
                                    buttonView.setButtonDrawable(R.drawable.checkbox_uncheck);
                                }
                            }
                        }
                    }
                });
                mQueChooseLayout.addView(mChoice[i]);
            }

            if (!"0".equals(mIQuestion.getAnswerid())) {
                for (int i = 0; i < getAnswer().length(); i++) {
                    int ci = (int) getAnswer().charAt(i) - 65;
                    if ((ci > -1) && (ci < choiceno)) {
                        mChoice[ci].setChecked(true);
                        mChoice[ci].setButtonDrawable(R.drawable.checkbox_checked);
                    }
                }
            }
            checkedImg();
            mQueChooseLayout.setVisibility(View.VISIBLE);
            mAnswerBtn.setVisibility(View.GONE);
            mSubmitBtn.setVisibility(View.VISIBLE);
        }
    }

    private void setButtonStatus() {
        mPrevBtn.setVisibility(View.VISIBLE);
        mNextBtn.setVisibility(View.VISIBLE);
        if (mErrorBooks.size() == 1) {
            mPrevBtn.setVisibility(View.GONE);
            mNextBtn.setVisibility(View.GONE);
        } else {
            if (mQuestionIndex == 0) {
                mPrevBtn.setVisibility(View.GONE);
            } else if (mQuestionIndex == mErrorBooks.size() - 1) {
                mNextBtn.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public int startTask(int taskId) {
        if (taskId == TASK_GET_USERANSWER) {
            mProgressDialog.setMessage("正在加载...");
            mProgressDialog.show();
        } else if (taskId == TASK_SUBMIT_ERRORANSWER) {
            mProgressDialog.setMessage("正在提交...");
            mProgressDialog.show();
        }
        return super.startTask(taskId);
    }

    private void initIaskuQuestion() {
        mIQuestion = new IaskuQuestion();
        mIQuestion.setQuestionno(mEbook.getQuestionno());
        mIQuestion.setQuestion_score(mEbook.getMaxScore());
        mIQuestion.setQuestiontype_name(mEbook.getQuestionTypeName());
        int que_type_id = IaskuUtil.getQuestionTypeId(this, mEbook.getQuestionTypeName());
        mIQuestion.setQuestion_type_id(que_type_id);
        switch (que_type_id) {
        case Constant.TYPE_DANX:
        case Constant.TYPE_DUOX:
        case Constant.TYPE_XUANZ:
            mIQuestion.setIsattach(Constant.ATTACH_NO);
            break;

        default:
            mIQuestion.setIsattach(Constant.ATTACH_YES);
            break;
        }
    }

    @Override
    public Status onTaskInBackground(int taskId, Bundle bundle) {
        switch (taskId) {
        case TASK_GET_USERANSWER: {
            initIaskuQuestion();
            IDataManager manager = DataManager.getInstance();
            manager.getUserAnswer(Constant.USER_IASKUNAME, mEbook.getExamid(), mEbook.getQuestionno(), mIQuestion);
        }
        case TASK_GET_QUESTIONTYPEBYID: {
            IDataManager manager = DataManager.getInstance();
            manager.getQuestionById(mIQuestion);
        }
            break;
        case TASK_SUBMIT_ERRORANSWER: {
            IDataManager manager = DataManager.getInstance();
            int isright = 0;
            String useranswer = mIQuestion.getUseranswer();
            String trueanswer = mIQuestion.getTrueanswer();
            if (trueanswer.equals(useranswer)) {
                isright = 1;
            } else {
                isright = 0;
            }
            ReturnData<String> mReturnData = manager.submitErrorUserAnswer(Constant.USER_IASKUNAME, mEbook.getExamid(),
                    mIQuestion.getQuestionno(), mIQuestion.getUseranswer(), mIQuestion.getIsattach(),
                    mIQuestion.getQuestion_score(), mIQuestion.getQuestiontype_id(),
                    IaskuUtil.getSubjectId(this,mEbook.getSubjectname()), isright,
                    mIQuestion.getSubmitTimes());
            return new Status(mReturnData);
        }
        case TASK_START_SYSTEMRECOMMAND: {
            IDataManager manager = DataManager.getInstance();
            manager.startSystemRecommand(mEbook.getExamid(), mIQuestion.getQuestionno(),
                    mIQuestion.getQuestion_score(), mIQuestion.getQuestion_type_id());
        }
            break;
        }
        return super.onTaskInBackground(taskId, bundle);
    }

    @Override
    public int onTaskComplete(int taskId, Status status) {
        switch (taskId) {
        case TASK_GET_USERANSWER:
            startTask(TASK_GET_QUESTIONTYPEBYID);
            break;
        case TASK_GET_QUESTIONTYPEBYID:
            setViewValue();
            break;
        case TASK_SUBMIT_ERRORANSWER:
            submitErrorAnswerOk(status);
            break;
        }
        return super.onTaskComplete(taskId, status);
    }

    private void submitErrorAnswerOk(Status status) {
        mProgressDialog.dismiss();
        if (status.code == 0) {
            BaseUtil.showText(this, "提交成功");
            startTask(TASK_START_SYSTEMRECOMMAND);
        }
    }
}
